﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Lasalara.Model
{
    public class Chapter : IEquatable<Chapter>
    {
        public string ChapterKey { get; set; }
        public string ChapterTitle { get; set; }
        public string Version { get; set; }
        public string AuthorEmail { get; set; }
        public string AuthorName { get; set; }
        public string Institution { get; set; }
        public bool Doctorate { get; set; }
        public bool AllowProposals { get; set; }
        public bool IsDownloaded { get; set; }
        public List<Question> Questions { get; set; }
        public Question CurrentQuestion { get; set; }
        public double Progress { get; set; }

        public string ProgressPercentage
        {
            get
            {
                if (IsDownloaded && Questions.Count == 0)
                {
                    return "-";
                }
                if (Progress > 0 && Progress < 1)
                {
                    return IsDownloaded ? "< 1%" : "";
                }
                else
                {
                    return IsDownloaded ? string.Format("{0}{1}", Math.Round(Progress, 0), "%") : "";
                }
                
            }
        }

        public static double GetChapterProgress(Chapter chapter)
        {
            return (double) chapter.Questions.Count(x => x.AnsweredDate > DateTime.Now) / chapter.Questions.Count * 100;
        }

        public static bool AreAllQuestionsAnswered(Chapter chapter)
        {
            return chapter.Questions.Count(x => x.AnsweredDate > DateTime.Now) == chapter.Questions.Count;
        }

        public void UpdateQuestionWithCurrentQuestion(Question question)
        {
            Questions[Questions.IndexOf(question)] = question;
        }

        #region IEquatable<Chapter> Members

        /// <summary>
        /// Checks if given chapter's key equals to this chapter's key
        /// </summary>
        /// /// <param name="other">Given chapter</param>
        public bool Equals(Chapter other)
        {
            if (other == null) return false;
            return ChapterKey == other.ChapterKey;
        }

        #endregion
    }
}